﻿using System;
using System.Xml;
using BasecampRestAPI;
using NUnit.Framework;

namespace TestBasecampRestAPI
{
	[TestFixture]
	public class TestXmlHelpers
	{
		[Test]
		public void ChildNodeText()
		{
			Assert.AreEqual("Inner text",
				XmlHelpers.ChildNodeText(GetElementForXml("<foo><child>Inner text</child></foo>"), "child"));
		}

		[Test]
		public void ChildNodeTextDefault()
		{
			Assert.AreEqual("Default",
				XmlHelpers.ChildNodeText(GetElementForXml("<foo><child>Inner text</child></foo>"), "bar", "Default"));
		}

		[Test]
		public void ParseBoolFalse()
		{
			Assert.IsFalse(XmlHelpers.ParseBool(GetElementForXml("<foo><child>false</child></foo>"), "child"));
		}

		[Test]
		public void ParseBoolTrue()
		{
			Assert.IsTrue(XmlHelpers.ParseBool(GetElementForXml("<foo><child>true</child></foo>"), "child"));
		}

		[Test]
		public void ParseDateTime()
		{
			XmlNode node =
				GetElementForXml("<foo><created-on type=\"datetime\">12-03-1969 16:45:45</created-on></foo>");
			DateTime expected = new DateTime(1969, 12, 03, 16, 45, 45);
			Assert.AreEqual(expected, XmlHelpers.ParseDateTime(node, "created-on"));
		}

		[Test]
		public void ParseDateTimeEmpty()
		{
			XmlNode node = GetElementForXml("<foo><created-on type=\"datetime\"></created-on></foo>");
			DateTime expected = new DateTime(1969, 12, 03, 16, 45, 45);
			Assert.AreEqual(expected, XmlHelpers.ParseDateTime(node, "created-on", expected));
		}

		[Test]
		public void ParseDateTimeNoNode()
		{
			XmlNode node = GetElementForXml("<foo></foo>");
			DateTime expected = new DateTime(1969, 12, 03, 16, 45, 45);
			Assert.AreEqual(expected, XmlHelpers.ParseDateTime(node, "created-on", expected));
		}

		[Test]
		public void ParseInteger()
		{
			Assert.AreEqual(1492,
				XmlHelpers.ParseInteger(GetElementForXml("<foo><child>1492</child></foo>"), "child"));
		}

		[Test]
		public void ParseIntegerEmpty()
		{
			Assert.AreEqual(-1,
				XmlHelpers.ParseInteger(GetElementForXml("<foo><child></child></foo>"), "child"));
		}

		[Test]
		public void DateString()
		{
			DateTime date = new DateTime(2009, 12, 03);
			Assert.AreEqual("2009-12-03", XmlHelpers.DateString(date));
		}

		[Test]
		public void EscapeXml()
		{
			Assert.AreEqual("&amp;", XmlHelpers.EscapeXml("&"));
			Assert.AreEqual("&lt;", XmlHelpers.EscapeXml("<"));
			Assert.AreEqual("&gt;", XmlHelpers.EscapeXml(">"));
			Assert.AreEqual("&quot;", XmlHelpers.EscapeXml("\""));
			Assert.AreEqual("&apos;", XmlHelpers.EscapeXml("'"));
		}

		private static XmlElement GetElementForXml(string xml)
		{
			return TestBasecamp.GetElementForXml(xml);
		}
	}
}
